<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加评分模版"
    :before-close="handleDialogClose"
  >
    <div class="content">
      <el-form :model="form" ref="formRef" :inline="true" label-width="auto">
        <el-row>
          <el-col :span="24">
            <el-form-item
              label="模版名称"
              prop="name"
              :rules="{
                required: true,
                message: '请输入模版名称',
                trigger: 'blur',
              }"
            >
              <el-input v-model="form.name" placeholder="请输入模版名称">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item
              label="评分维度"
              :rules="{
                required: true,
              }"
            >
              <div class="outer-box">
                <div
                  class="inner-box"
                  v-for="(data, index) in form.tName"
                  :key="index"
                >
                  <el-input
                    v-model="form.tName[index].name"
                    placeholder="最多10个字"
                    maxlength="10"
                    style="width: 300px"
                  />
                  <el-icon v-if="index !== 0" @click="upData(index)"
                    ><SortUp
                  /></el-icon>
                  <div v-else class="zhanwei" />
                  <el-icon
                    v-if="index !== form.tName.length - 1"
                    @click="downData(index)"
                  >
                    <SortDown />
                  </el-icon>
                  <div v-else class="zhanwei" />
                  <el-icon @click="delData(index)"><Delete /></el-icon>
                </div>
                <el-button @click="addData" :disabled="form.tName.length >= 10">
                  <span style="color: rgb(64, 158, 255)"> + 添加</span
                  >{{ "(" + form.tName.length + "/10)" }}
                </el-button>
              </div>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="设为课程的默认评分模板" prop="courseArr">
              <el-select
                v-model="form.courseArr"
                multiple
                placeholder="请选择课程名称"
                clearable
                style="width: 240px"
              >
                <el-option
                  v-for="item in courseList"
                  :key="item.cid"
                  :label="
                    item.code === '1' ? item.name + '(已有关联模板)' : item.name
                  "
                  :value="item.cid"
                  :disabled="
                    item.code === '1' && !form.initCourseArr.includes(item.cid)
                  "
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleDialogClose()">取消</el-button>
        <el-button type="primary" @click="save()"> 保存 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import {
  saveTemplateAPI,
  updateTemplateAPI,
  getCourseListInTemplateAPI,
  getTemplateDetailAPI,
} from "@/api/interaction/comment";
const { proxy } = getCurrentInstance();
// 变量--------------------------------------------------------------------------------------------------------------------
const loading = ref(false);
const dialogVisible = ref(false);

const data = reactive({
  form: {
    id: null,
    name: "",
    tName: [], // 评分维度 "tName":[{id,"name":"1d21",orderNum}]
    courseArr: [], // 设为课程的默认评分模板
    courseId: null, // courseArr 的逗号分隔
    delName: [], // 已有id且被删除的评分维度
    initCourseArr: [],
  },
});

const { form } = toRefs(data);

const formRef = ref(null);
const courseList = ref([]);

const emits = defineEmits(["refreshPage"]);

// 事件--------------------------------------------------------------------------------------------------------
function openW(row) {
  if (row) {
    getDetail(row.id);
  } else {
    form.value = {
      id: null,
      name: "",
      tName: [],
      courseArr: [],
      courseId: null,
      delName: [],
      initCourseArr: [],
    };
  }
  getCourseList();
  dialogVisible.value = true;
  //makeupDetailList(row);
}

function handleDialogClose() {
  dialogVisible.value = false;
  resetW();
}

function resetW() {
  form.value.tName = [];
  form.value.delName = [];
  if (formRef.value) {
    formRef.value.resetFields();
  }
}

function getDetail(id) {
  loading.value = true;
  getTemplateDetailAPI({ id })
    .then((response) => {
      loading.value = false;
      form.value = response.data[0];
      form.value.courseArr = form.value.courseId.split(",");
      form.value.initCourseArr = JSON.parse(
        JSON.stringify(form.value.courseArr)
      );
      form.value.delName = [];
    })
    .catch(() => {
      loading.value = false;
    });
}

function save() {
  let list = form.value.tName.filter((data) => {
    return data.name;
  });
  list.forEach((element, index) => {
    element.orderNum = index + 1;
  });
  if (form.value.courseArr.length > 0)
    form.value.courseId = form.value.courseArr.join(",");
  else form.value.courseId = "0";
  proxy.$refs["formRef"].validate((valid) => {
    if (valid) {
      if (list.length === 0) {
        proxy.$modal.msgError("至少有一个评分维度且已命名");
        return;
      }
      form.value.tName = list;
      saveData();
    } else {
      proxy.$modal.msgError("模版名称不可为空");
    }
  });
}

function saveData() {
  if (form.value.id) {
    updateTemplateAPI(form.value)
      .then((response) => {
        proxy.$modal.msgSuccess("保存成功");
        handleDialogClose();
        refreshParent();
      })
      .catch(() => {
        loading.value = false;
      });
  } else {
    saveTemplateAPI(form.value)
      .then((response) => {
        proxy.$modal.msgSuccess("保存成功");
        handleDialogClose();
        refreshParent();
      })
      .catch(() => {
        loading.value = false;
      });
  }
}

function addData() {
  form.value.tName.push({ name: "", id: null, isDelete: 0 });
}

function upData(index) {
  let temp = form.value.tName[index];
  form.value.tName[index] = form.value.tName[index - 1];
  form.value.tName[index - 1] = temp;
}

function downData(index) {
  let temp = form.value.tName[index];
  form.value.tName[index] = form.value.tName[index + 1];
  form.value.tName[index + 1] = temp;
}

function delData(index) {
  if (form.value.tName[index].id) {
    form.value.tName[index].isDelete = 1;
    form.value.delName.push(form.value.tName[index]);
  }
  form.value.tName = form.value.tName.filter((data, i) => {
    return i !== index;
  });
}

function refreshParent() {
  emits("refreshPage");
}

// 方法----------------------------------------------------------------------------------------------------------
// 课程
function getCourseList() {
  loading.value = true;
  getCourseListInTemplateAPI({
    pageSize: 9999,
    pageNum: 1,
  }).then((response) => {
    courseList.value = response.data;
    loading.value = false;
  });
}

defineExpose({ openW }); // 用于父组件调用
</script>

<style lang="scss" scoped>
.inner-box {
  margin-bottom: 10px;
  display: flex;
  flex-direction: row;
  align-items: center;
  i {
    margin-left: 10px;
  }
  .zhanwei {
    width: 24px;
  }
}
</style>
